//
//  CAPTabbar.swift
//  CAPSwift
//
//  Created by captain on 16/4/17.
//  Copyright © 2016年 captain. All rights reserved.
//

import UIKit

// 声明协议
protocol CAPTabBarDelegate: NSObjectProtocol{
    // 协议方法
    func composeButtonClick()
}


class CAPTabBar: UITabBar {
    
    // MARK: - 代理属性，weak
    weak var capDelegate: CAPTabBarDelegate?
    

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置控件
    func setupUI(){
        addSubview(composeButton)
    }
    
    
    // MARK: - 点击事件
    @objc private func composeButtonClick(){
        
        capDelegate?.composeButtonClick()
    }
    
    
    // MARK: - 对子控件布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = SWIDTH / 5
        
        var index: CGFloat = 0
        //遍历子控件
        for value in self.subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                value.frame.origin.x = index * width
                
                value.frame.size.width = width
                
                index++
                //中间放一个+按钮
                if index == 2 {
                    index++
                }
            }

        }
        //按钮在中间
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
    }
    
    
    // MARK: - 懒加载button
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        //背景图
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        //添加image
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        //大小相等
        button.sizeToFit()
        //添加点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)

        
        return button
    }()
    

    
}
